﻿using System;
using System.Messaging;
using System.Configuration;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using System.Data.OleDb;

namespace Derrick.Web
{
    public class CometMessage
    {
        public string Message { get; set; }
        public List<int> SentToClients = new List<int>();
        public DateTime LastUpdated { get; set; }
    }
        

    public sealed class QueueMessage
    {

        //public DateTime LastUpdated { get; set; }
        //public string Message { get; set; }

        #region Singleton specific

        private static volatile QueueMessage _instance;
        private static object _syncRoot = new object();

        public static QueueMessage Instance
        {
            get
            {
                if (null == _instance)
                {
                    lock (_syncRoot)
                    {
                        if (_instance == null)
                        {
                            _instance = new QueueMessage();
                        }
                    }
                }
                return _instance;
            }
        }

        #endregion Singleton specific

        private static DateTime _lastUpdated;
        private static string _message;

        private QueueMessage()
        {

        }

        public DateTime LastUpdated
        {
            get { return _lastUpdated; }
            set { _lastUpdated = value; }
        }

        public string Message
        {
            get { return _message; }
            set { _message = value; }
        }

        public List<CometMessage> Messages = new List<CometMessage>();

    }

    public class SendMessageEventArgs : EventArgs
    {
        public Request Request { get; set; }
        public DateTime Timestamp { get; set; }
        public Client Client { get; set; }
        public string Message { get; set; }

    }


    public class MessageLoop
    {
        protected MessageQueue _intranetBannerQueue;
        protected Thread _messageHandlingThread = null;
        protected TraceSwitch _traceSwitch;
        
        //Send message event
        public delegate void SendMessageEventHandler(object sender, SendMessageEventArgs args);
        public event SendMessageEventHandler SendMessageEvent;

        public MessageLoop()
        {
            _traceSwitch = new TraceSwitch("TraceLevelSwitch", "Comet Tracing");


            string msgQueueName = ConfigurationManager.AppSettings["CometQueue"];
            Trace.WriteLineIf(_traceSwitch.TraceInfo, "Intranet queue name: " + msgQueueName);
            _intranetBannerQueue = new MessageQueue(msgQueueName);
            Trace.WriteLineIf(_traceSwitch.TraceInfo, "New message queue instance created.");

            _messageHandlingThread = new Thread(new ThreadStart(messageLoop));
            _messageHandlingThread.Start();


        }


        private void messageLoop()
        {
            try
            {
                while (true)
                {
                    Trace.WriteLineIf(_traceSwitch.TraceInfo, "Awaiting message from the message queue.");
                    Message msg = _intranetBannerQueue.Receive();  //holds thread until message received
                    Trace.WriteLineIf(_traceSwitch.TraceInfo, "Message retrieved from the message queue.");

                    SendMessageEventArgs args = new SendMessageEventArgs();
                    args.Timestamp = DateTime.Now;

                    msg.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                    string cometMsg = msg.Body.ToString();
                    args.Message = cometMsg;

                    //OleDbConnection conn = new OleDbConnection();
                    //using (OleDbCommand cmd = new OleDbCommand())
                    //{
                    //    string insertMsg = "insert into comettest_messages (message_id, message, last_updated) values (";
                    //    insertMsg += "comettest_messages_seq.nextval, '" + cometMsg.Replace(@"'", @"''") + "', SYSDATE)";
                    //    cmd.CommandText = insertMsg;
                    //    cmd.CommandType = System.Data.CommandType.Text;
                    //    cmd.Connection = conn;
                    //    cmd.ExecuteNonQuery();

                    //}


                    if (SendMessageEvent != null)
                    {
                        SendMessageEvent(this, args);
                        Trace.WriteLineIf(_traceSwitch.TraceVerbose, "Message loop raised SendMessage event.");
                    }
                    
                    Trace.WriteLineIf(_traceSwitch.TraceInfo, "Message is: " + cometMsg);

                }

            }
            catch (Exception ex)
            {
                Trace.WriteLineIf(_traceSwitch.TraceError, ex.ToString(), "COMET Server");
            }

        }



    }

}